<?php
/**
 * Created by IntelliJ IDEA.
 * User: luwei
 * Date: 2017/7/1
 * Time: 23:33
 */

namespace app\modules\api\models;


use app\hejiang\ApiResponse;
use app\models\Dynamic;
use app\models\Goods;

use yii\data\Pagination;

class DynamicListForm extends ApiModel
{
     public $model;

    public $store_id;
    public $title;
    public $sort;
    public $is_chosen;
	public $pic_list;
	public $url;

	public $page;
    public $limit;

    public function search()
    {
		
        if (!$this->validate())
            return $this->errorResponse;
        $query = Dynamic::find()->alias('g')->where([
            'g.is_delete' => 0,
            'g.is_chosen' => 0,
			
        ]);
        if ($this->store_id)
            $query->andWhere(['g.store_id' => $this->store_id]);
  
     
        $count = $query->count();

        $pagination = new Pagination(['totalCount' => $count, 'pageSize' => $this->limit, 'page' => $this->page - 1]);
    
            $query->orderBy('g.sort ASC, g.addtime DESC');
       

        $list = $query
           
            ->select('g.*')
            ->limit($pagination->limit)
            ->offset($pagination->offset)
            ->asArray()->groupBy('g.id')->all();

		foreach($list as $key=>$val){
			
			$list[$key]['pic_list'] = unserialize($val['pic_list']);
			$list[$key]['addtime'] =date('Y-m-d H:i:s',$val['addtime']);
			//$list[$key]['sub_title'] = $val['title'];
			$list[$key]['title'] =mb_strcut($val['title'],0,64,'utf-8');
			if($val['goods_id']){
				$GoodsInfo = Goods::find()->where([
					'id' => $val['goods_id'],
				])->select('price,virtual_sales')->asArray()->one();
			}
			$list[$key]['price'] =$GoodsInfo['price']?$GoodsInfo['price']:0;
			$list[$key]['virtual_sales'] =$GoodsInfo['virtual_sales']?$GoodsInfo['virtual_sales']:0;
		}
        $data = [
            'row_count' => $count,
            'page_count' => $pagination->pageCount,
            'list' => $list,
        ];
	
        return new ApiResponse(0, 'success', $data);
    }

   

}
